package com.example.dormitory_system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dormitory_system.domain.dto.LoginDTO;
import com.example.dormitory_system.domain.dto.student.StudentInfoUpdateDTO;
import com.example.dormitory_system.domain.dto.sysuser.RegisterDTO;
import com.example.dormitory_system.domain.enetiy.Student;
import com.example.dormitory_system.domain.vo.student.StuLoginVO;
import com.example.dormitory_system.domain.vo.student.StudentInfoVO;
import com.example.dormitory_system.domain.vo.tsysuser.FindStudentVO;
import com.example.dormitory_system.domain.vo.user.LoginVO;
import com.example.dormitory_system.enums.ResultCode;
import com.example.dormitory_system.exception.ServiceException;
import com.example.dormitory_system.service.StudentService;
import com.example.dormitory_system.mapper.StudentMapper;
import com.example.dormitory_system.utils.BCryptUtils;
import com.example.dormitory_system.utils.ExcelUtil;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author keenan
* @description 针对表【tb_student(学生表)】的数据库操作Service实现
* @createDate 2025-03-26 15:31:26
*/
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student>
    implements StudentService {
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public StuLoginVO login(LoginDTO loginDTO) {
        // 1. 通过username查询用户
        if (StrUtil.isEmpty(loginDTO.getUsername()) || StrUtil.isEmpty(loginDTO.getPassword())) {
            throw new ServiceException(ResultCode.FAILED_LOGIN);
        }

        Student student = studentMapper.selectOne(new LambdaQueryWrapper<Student>().eq(Student::getUsername, loginDTO.getUsername()));

        // 2. 判断用户是否存在
        if (student == null) {
            throw new ServiceException(ResultCode.FAILED_LOGIN);
        }

        // 3. 比较密码是否匹配
        if (!BCryptUtils.matchesPassword(loginDTO.getPassword(), student.getPassword())) {
            throw new ServiceException(ResultCode.FAILED_LOGIN);
        }

        // 4. 获取HttpSession并存储用户信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpSession session = attributes.getRequest().getSession();
            session.setAttribute("userId",student.getStudentId());
            session.setAttribute("role", 1);
        }

        // 5. 返回用户角色
        return new StuLoginVO( student.getStudentId(), 1);
    }

    @Override
    public int register(RegisterDTO registerDTO) {
        // 1. 参数校验
        if (StrUtil.isEmpty(registerDTO.getName()) || StrUtil.isEmpty(registerDTO.getUsername()) || StrUtil.isEmpty(registerDTO.getPassword())) {
            throw new ServiceException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        if (studentMapper.selectOne(new LambdaQueryWrapper<Student>().eq(Student::getUsername, registerDTO.getUsername())) != null) {
            throw new ServiceException(ResultCode.AILED_USER_EXISTS);
        }

        Student student = new Student();
        student.setName(registerDTO.getName());
        student.setUsername(registerDTO.getUsername());
        student.setPassword(BCryptUtils.encryptPassword(registerDTO.getPassword()));
        return studentMapper.insert(student);
    }

    public void importStudents(MultipartFile file) throws IOException {
        try {
            List<Student> students = ExcelUtil.readStudentsFromExcel(file.getInputStream());
            for (Student student : students) {
                System.out.println(666);
                student.setPassword(BCryptUtils.encryptPassword(student.getPassword()));
            }
            System.out.println(777);
            saveBatch(students);
            System.out.println(888);
        } catch (Exception e) {
            throw new RuntimeException("Failed to import students from Excel", e);
        }
    }

    @Override
    public StudentInfoVO info(Long studentId) {

        Student student = studentMapper.selectOne(new LambdaQueryWrapper<Student>().eq(Student::getStudentId, studentId));
        if (student == null)
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        StudentInfoVO studentInfoVO = new StudentInfoVO();
        BeanUtil.copyProperties(student, studentInfoVO);
        return studentInfoVO;
    }

    @Override
    public int updateInfo(StudentInfoUpdateDTO studentInfoUpdateDTO) {
        // 1. 验证学生ID是否存在
        if (studentInfoUpdateDTO.getStudentId() == null) {
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        
        // 2. 检查学生是否存在
        Student student = studentMapper.selectById(studentInfoUpdateDTO.getStudentId());
        if (student == null) {
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        
        // 3. 调用mapper的动态更新方法
        return studentMapper.updateStudentInfo(studentInfoUpdateDTO);
    }

    @Override
    public List<FindStudentVO> findStudent(String roomName, String buildingName) {
        System.out.println(roomName);
        System.out.println(buildingName);
        return studentMapper.selectList(new LambdaQueryWrapper<Student>()
                        .eq(Student::getRoomName, roomName)
                        .eq(Student::getBuildingName, buildingName))
                .stream()
                .map(student -> {
                    FindStudentVO findStudentVO = new FindStudentVO();
                    BeanUtil.copyProperties(student, findStudentVO);
                    return findStudentVO;
                })
                .collect(Collectors.toList());
    }
}